﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SignalBox.Core.Data
{
    public class DataLayer
    {

        private static DataLayer _instance;

        static DataLayer()
        {
            _instance = new DataLayer();
        }

        public static DataLayer Instance
        {
            get
            {
                return _instance;
            }
        }

        private string _trackFile;

        public string TrackFile
        {
            get
            {
                return _trackFile;
            }
            set
            {
                _trackFile = value;
                _layoutInfo = null;
                _trackList = null;
                //LoadData();
            }
        }

        private LayoutInfo _layoutInfo;
        private List<Track> _trackList;

        public LayoutInfo LayoutInfo
        {
            get
            {
                if (String.IsNullOrEmpty(TrackFile))
                    return null;

                if (_layoutInfo != null)
                    return _layoutInfo;

                LoadData();

                return _layoutInfo;
            }
            set
            {
                _layoutInfo = value;
            }
        }

        public List<Track> TrackList
        {
            get
            {
                if (String.IsNullOrEmpty(TrackFile))
                    return null;

                if (_trackList != null)
                    return _trackList;

                LoadData();

                return _trackList;
            }
            set
            {
                _trackList = value;
            }
        }

        private void LoadData()
        {
            XDocument doc = XDocument.Load(TrackFile);

            _layoutInfo = new LayoutInfo();
            _layoutInfo.FromXml(doc.Root.Element("LayoutInfo"));


            _trackList = Track.FromXml(doc.Root.Element("Tracks"));


        }

        public void Save()
        {
            XDocument doc = new XDocument();

            doc.Add(new XElement("Layout",
                _layoutInfo.ToXml(),
                new XElement("Tracks",
                    from Track t in _trackList
                    select t.ToXml())));


            doc.Save(TrackFile);

        }
    }
}
